import {useState, useEffect, createRef} from 'react';
import {connect} from "react-redux";
import Taro, {useLoad, useDidShow} from '@tarojs/taro'
import {View, Button} from '@tarojs/components'
import {Swiper, SwiperItem, Avatar, Image, Overlay, Loading} from '@nutui/nutui-react-taro';
import {AtButton, AtModal, AtModalAction, AtModalContent, AtModalHeader} from "taro-ui";
import './index.less'
import getBaseUrl from "../../service/baseUrl";
import defaultAvatar from '../../assets/defaultAvatar.png';
import {wxLogin} from "../../utils";

const base = getBaseUrl();
const leaders = ['152251826011'];

function Index(props) {
  const kefuBtnRef = createRef();
  const isLogin = Taro.getStorageSync("isLogin");
  const {
    dispatch,
    myCoupons,
    isTeamLeader,
    myCouponsActive,
    phoneNumberInStore,
    balance,
    integral,
    pointList = []
  } = props;
  const [phoneNumber, setNumber] = useState(Taro.getStorageSync("phoneNumber") || phoneNumberInStore);
  const [isOpened, setOpen] = useState(false)
  // const [isTeamLeader, setIsTeamLeader] = useState(false)
  const [loginLoading, setLoginLoading] = useState(false)
  console.log('我的页面', props);
  const totalIntegral = pointList.length ? pointList.reduce((pre, cur) => cur.pointBalance + pre, 0) : 0
  useLoad(() => {
    console.log('Page loaded.')
  })
  useDidShow(() => {
    wxLogin();
    if (isLogin) {
      dispatch({
        type: 'wallet/getBalance'
      });
      dispatch({
        type: 'stations/getChargingOrderInfo'
      });
      dispatch({
        type: 'stations/getMyCoupons'
      })
    }
  });
  useEffect(() => {
    const phone = Taro.getStorageSync("phoneNumber");
    setNumber(phone)
    // setIsTeamLeader( leaders.some((l) => l === phoneNumberInStore))
  }, [phoneNumberInStore, isLogin]);
  console.log('phone', phoneNumberInStore);
  console.log('isTeamLeader', isTeamLeader);
  const WrapperStyle = {
    display: 'flex',
    height: '100%',
    alignItems: 'center',
    justifyContent: 'center'
  }
  return (
    <View className='mineWrap'>
      <Overlay visible={loginLoading}>
        <div style={WrapperStyle}>
          <Loading direction='vertical'>登录中,请稍候...</Loading>
        </div>
      </Overlay>
      <div className='userInfo'>
        <div>
          <Avatar
            size='60'
            src={defaultAvatar}
            alt='暂时无法查看'
          />
        </div>
        {
          isLogin ? <div>
            <div className='title'>{phoneNumber}</div>
            <div className='description'>
              金冠智充用户
            </div>
          </div> : <div>
            <div className='title'>
              <Button
                plain
                style={{border: 'none'}}
                openType='getPhoneNumber'
                onGetPhoneNumber={(e) => {
                  const accessToken = Taro.getStorageSync('access_token')
                  // getUserProfile({...e.detail})
                  const {detail: {iv, encryptedData} = {}} = e;
                  if (encryptedData && iv) {
                    // wxLogin();
                    setLoginLoading(true);
                    setTimeout(() => {
                      const session_key = Taro.getStorageSync('session_key') || '';
                      const openid = Taro.getStorageSync('openid') || '';
                      console.log('openid', openid);
                      console.log('session_key', session_key);
                      if (openid && session_key) {
                        // console.log('openid', openid);
                        Taro.request({
                          url: `${base}/wxLogin`,
                          data: {
                            encryptedData,
                            iv,
                            openid,
                            sessionKey: session_key
                          },
                          header: {
                            "content-type": "application/json",
                            "appid": 'wx52f6aba688ce70f6',
                            "Authorization": accessToken ? "Bearer " + accessToken : '',
                          },
                          method: "POST",
                        }).then((res) => {
                          const {
                            data: {
                              code,
                              data: {phoneNumber: phone, token} = {}
                            } = {}
                          } = res;
                          console.log('wxLogin', res);
                          // console.log('获取手机号成功的RES', res);
                          if (code === 200) {
                            Taro.showToast({
                              title: '登录成功',
                              icon: 'success'
                              // duration: 2000
                            })
                            Taro.setStorageSync('isLogin', true);
                            Taro.setStorageSync('access_token', token);
                            Taro.setStorageSync('phoneNumber', phone);
                            dispatch({
                              type: 'app/upState',
                              payload: {
                                phoneNumberInStore: phoneNumber
                              }
                            })
                            dispatch({
                              type: 'wallet/getBalance'
                            });
                            dispatch({
                              type: 'stations/getChargingOrderInfo'
                            })
                            setLoginLoading(false);
                          } else {
                            Taro.showToast({
                              title: '登录失败,请重试',
                              icon: 'none',
                              // duration: 2000
                            });
                            setLoginLoading(false);
                          }
                        });
                      }
                    }, 100)
                  }
                }}
              >您好,请登录</Button>
            </div>
          </div>
        }
      </div>
      <div className='moneyInfo'>
        <div className='cards'>
          <div className='card'
               onClick={() => {
                 if (!isLogin) {
                   setOpen(true)
                 } else {
                   Taro.navigateTo({url: "/moduleB/pages/wallet/index"})
                 }
               }}
          >
            <div className='cardNum'>{isLogin ? balance.toFixed(2) : '0.00'}</div>
            <div>余额</div>
          </div>
          <div className='card'
               onClick={() => {
                 if (!isLogin) {
                   setOpen(true)
                 } else {
                   Taro.navigateTo({url: "/moduleB/pages/wallet/index"})
                 }
               }}
          >
            <div className='cardNum'>{isLogin ? '0.00' : '0.00'}</div>
            <div>赠送</div>
          </div>
          <div
            className='card'
            // onClick={() => {
            //       if (!isLogin){
            //           setOpen(true)
            //       }else {
            //           Taro.navigateTo({url: "/moduleB/pages/wallet/IntegralRecharge"})
            //       }
            // }}
          >
            <div className='cardNum'>{isLogin ? (totalIntegral / 100).toFixed(2) : 0}</div>
            <div>储值</div>
          </div>
          <div
            className='card'
            onClick={() => {
              if (!isLogin) {
                setOpen(true);
              } else {
                Taro.navigateTo({url: "/moduleA/pages/coupons/index"})
              }
            }}
          >
            <div className='cardNum'>{isLogin ? myCouponsActive.length : 0}</div>
            <div>优惠券</div>
          </div>
        </div>
      </div>
      <div className='chargeWarp'>
        <div className='cards'>
          <div className='card'
               onClick={() => {
                 if (!isLogin) {
                   setOpen(true);
                 } else {
                   Taro.navigateTo({url: "/moduleB/pages/wallet/recharge"})
                 }
               }}
          >
            <div><i className='icon icon-tixian'/></div>
            <div>我要充值</div>
          </div>
          <div
            className='card'
            onClick={() => {
              if (!isLogin) {
                setOpen(true);
              } else {
                dispatch({
                  type: 'stations/goChargingPage'
                })
              }
            }}
          >
            <div><i className='icon icon-car'/></div>
            <div>正在充电</div>
          </div>
          <div
            className='card'
            onClick={() => {
              if (!isLogin) {
                setOpen(true)
              } else {
                Taro.navigateTo({url: "/moduleB/pages/wallet/withdraw"})
              }
            }}
          >
            <div><i className='icon icon-tuikuan'/></div>
            <div>退款申请</div>
          </div>
          <div
            className='card'
            onClick={() => {
              if (!isLogin) {
                setOpen(true)
              } else {
                Taro.navigateTo({url: "/moduleA/pages/order/index"})
              }
            }}
          >
            <div><i className='icon icon-quanbudingdan'/></div>
            <div>订单记录</div>
          </div>
          <div
            className='card'
            onClick={() => {
              if (!isLogin) {
                setOpen(true)
              } else {
                dispatch({
                  type: 'recharge/setState',
                  payload: {
                    current: 1
                  }
                })
                Taro.navigateTo({url: "/moduleA/pages/trade/index"})
              }
            }}
          >
            <div><i className='icon icon-chongzhijilu'/></div>
            <div>充值记录</div>
          </div>
          {/*<div className='card' onClick={() => Taro.navigateTo({url: '/pages/cars/index'})}>*/}
          {/*  <div><i className='icon icon-zuchecheliang' /></div>*/}
          {/*  <div>车辆管理</div>*/}
          {/*</div>*/}
          <div
            className='card'
            onClick={() => {
              // Taro.showToast({
              //     title: '功能开发中',
              //     icon: 'loading'
              // })
              if (!isLogin) {
                setOpen(true)
              } else {
                Taro.navigateTo({url: "/moduleA/pages/invoice/index"})
                // Taro.showToast({
                //     title: '功能开发中',
                //     icon: 'loading'
                // })
                // Taro.chooseInvoiceTitle({
                //   success: (Res) => {
                //     console.log('成功的', Res)
                //     Taro.chooseInvoice({
                //       success: (Res1) => {
                //           console.log('成功的', Res1);
                //           Taro.navigateTo('/pages/mine/index')
                //       },
                //       fail: (Res2) => console.log('失败的', Res2),
                //       complete: (Res3) => console.log('完成的', Res3),
                //     })
                //   },
                //   fail: (Res) => console.log('失败的', Res),
                //   complete: (Res) => console.log('完成的', Res),
                // })
              }
            }}
          >
            <div><i className='icon icon-fapiao'/></div>
            <div>发票</div>
          </div>
          {/*<div*/}
          {/*  className='card'*/}
          {/*  onClick={() => {*/}
          {/*    Taro.navigateTo({url: "/moduleA/pages/guide/index"})*/}
          {/*  }}*/}
          {/*>*/}
          {/*  <div><i className='icon icon-zhinanzhidao' /></div>*/}
          {/*  <div>充电指南</div>*/}
          {/*</div>*/}
          {/*<div*/}
          {/*  className='card'*/}
          {/*  onClick={() => {*/}
          {/*    Taro.navigateTo({url: "/pages/vinCharge/index"})*/}
          {/*  }}*/}
          {/*>*/}
          {/*  <div><i className='icon icon-chejiahao' /></div>*/}
          {/*  <div>VIN充电</div>*/}
          {/*</div>*/}
          {/*<div className='card'>*/}
          {/*  <div><i className='icon icon-kefu' /></div>*/}
          {/*  <div>联系客服</div>*/}
          {/*  <Button openType='contact' className='contactBtn'>联系客服</Button>*/}
          {/*</div>*/}
          <div
            className='card'
            onClick={() => {
              // Taro.chooseLicensePlate({
              //   complete: (res) => {
              //     console.log('complete', res)
              //   }
              // })
              // Taro.showToast({
              //     title: '功能开发中',
              //     icon: 'loading'
              // })
              if (!isLogin) {
                setOpen(true)
              } else {
                Taro.navigateTo({
                  url: '/moduleB/pages/cars/index'
                })
                dispatch({
                  type: 'cars/jumpCar'
                })
              }
            }}
          >
            <div><i className='icon icon-zuchecheliang'/></div>
            <div>我的车辆</div>
          </div>
          <div
            className='card'
            onClick={() => {
              if (!isLogin) {
                setOpen(true)
              } else if (!isTeamLeader) {
                Taro.showToast({
                  title: '您还不是车队管理员,无法进行操作',
                  icon: 'none',
                  duration: 2000
                })
              } else {
                Taro.navigateTo({url: "/moduleB/pages/wallet/teamAccount"})
              }
            }}
          >
            <div><i className='icon icon-chedui'/></div>
            <div>我的车队</div>
          </div>
          <div
            className='card'
            onClick={() => {
              if (!isLogin) {
                setOpen(true)
              } else {
                Taro.navigateTo({url: "/moduleA/pages/order/bookOrder"})
              }
            }}
          >
            <div><i className='icon icon-pingjia'/></div>
            <div>我的预约</div>
          </div>
          <div
            className='card'
            onClick={() => {
              if (!isLogin) {
                setOpen(true)
              } else {
                Taro.navigateTo({url: "/moduleB/pages/aboutUs/index"})
              }
            }}
          >
            <div><i className='icon icon-guanyuwomen'/></div>
            <div>关于我们</div>
          </div>
          <div
            className='card'
            onClick={() => {
              if (!isLogin) {
                setOpen(true)
              } else {
                Taro.navigateTo({url: "/moduleB/pages/setting/index"})
              }
            }}
          >
            <div><i className='icon icon-shezhi'/></div>
            <div>设置</div>
          </div>
        </div>
      </div>
      <View>
        <Swiper
          height={85}
          className='swiperWrap'
          // className='test-h'
          indicatorColor='#999'
          indicatorActiveColor='#333'
          // vertical
          circular
          indicatorDots
          autoplay
        >
          <SwiperItem>
            {/*<Image mode='aspectFill' src='https://wanyulong-cdn-1313248182.cos.ap-nanjing.myqcloud.com/bg1.jpg'/>*/}
            <Image mode='aspectFill'
                   src='https://jgdq.obs.cn-southwest-2.myhuaweicloud.com/jgy/images/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241203095311.jpg'/>
          </SwiperItem>
          <SwiperItem>
            <Image mode='aspectFill'
                   src='https://jgdq.obs.cn-southwest-2.myhuaweicloud.com/jgy/images/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241203095322.jpg'/>
          </SwiperItem>
        </Swiper>
      </View>
      <AtModal isOpened={isOpened}>
        <AtModalHeader>温馨提示</AtModalHeader>
        <AtModalContent>
          <View className='modalContent'>
            请先登录再进行操作
          </View>
        </AtModalContent>
        <AtModalAction>
          <View className='modalFooter'>
            <AtButton
              plain
              style={{border: 'none'}}
              onClick={() => setOpen(false)}
            >取消</AtButton>
            <AtButton
              plain
              style={{border: 'none'}}
              openType='getPhoneNumber'
              onGetPhoneNumber={(e) => {
                const accessToken = Taro.getStorageSync('access_token')
                const {detail: {iv, encryptedData} = {}} = e;
                if (encryptedData && iv) {
                  // wxLogin();
                  setOpen(false);
                  setLoginLoading(true);
                  setTimeout(() => {
                    const session_key = Taro.getStorageSync('session_key') || '';
                    const openid = Taro.getStorageSync('openid') || '';
                    if (openid && session_key) {
                      Taro.request({
                        url: `${base}/wxLogin`,
                        data: {
                          encryptedData,
                          iv,
                          openid,
                          sessionKey: session_key
                        },
                        header: {
                          "content-type": "application/json",
                          "appid": 'wx52f6aba688ce70f6',
                          "Authorization": accessToken ? "Bearer " + accessToken : '',
                        },
                        method: "POST",
                      }).then((res) => {
                        const {
                          data: {
                            code, data: {
                              phoneNumber: phone, token
                            } = {}
                          } = {}
                        } = res;
                        console.log('wxLogin', res);
                        if (code === 200) {
                          Taro.showToast({
                            title: '登录成功',
                            icon: 'success'
                            // duration: 2000
                          })
                          Taro.setStorageSync('isLogin', true);
                          Taro.setStorageSync('access_token', token);
                          Taro.setStorageSync('phoneNumber', phone);
                          dispatch({
                            type: 'app/upState',
                            payload: {
                              phoneNumberInStore: phoneNumber
                            }
                          })
                          dispatch({
                            type: 'wallet/getBalance'
                          });
                          dispatch({
                            type: 'stations/getChargingOrderInfo'
                          })
                          setLoginLoading(false);
                        } else {
                          Taro.showToast({
                            title: '登录失败,请重试',
                            icon: 'none'
                            // duration: 2000
                          })
                        }
                      });
                    }
                  }, 100)
                }
              }}
            >确定</AtButton>
          </View>
        </AtModalAction>
      </AtModal>
    </View>
  )
}

function mapStateToProps({
                           app = {},
                           wallet = {},
                           stations: {
                             chargingOrderInfo = {},
                             myCoupons = [],
                             myCouponsActive = [],
                           } = {},
                           loading: {effects: {"news/load": loading = false} = {}} = {},
                         }) {
  return {
    ...app,
    ...wallet,
    chargingOrderInfo,
    myCoupons,
    myCouponsActive,
    loading,
  };
}

export default connect(mapStateToProps)(Index);
